# stories/middleware.py
from django.shortcuts import redirect
from django.contrib import messages
from django.urls import reverse
from django.http import HttpResponseForbidden

class LoginRequiredMiddleware:
    """
    中间件：为需要登录的页面提供友好的提示
    """
    
    def __init__(self, get_response):
        self.get_response = get_response
        # 定义不需要登录的路径
        self.exempt_paths = [
            '/register/',
            '/login/',
            '/',
            '/library/',
            '/leaderboard/',
            '/story/',
            '/ajax/search/',
        ]

    def __call__(self, request):
        # 检查请求路径是否需要登录
        if not request.user.is_authenticated:
            # 检查当前路径是否在豁免列表中
            path = request.path
            needs_auth = True
            
            # 检查是否在豁免路径中
            for exempt_path in self.exempt_paths:
                if path.startswith(exempt_path):
                    needs_auth = False
                    break
                    
            # 特殊处理故事详情页面 - 允许未登录用户查看已发布的故事
            if path.startswith('/story/') and 'stories:story_detail' in request.resolver_match.view_name:
                needs_auth = False
                
            # 如果需要认证但用户未登录
            if needs_auth:
                # 添加友好的提示消息
                messages.info(request, '当前页面需要登录才能进行访问，请先登录')
                # 重定向到登录页面
                login_url = reverse('stories:login')
                # 保留用户想要访问的页面，登录后可以跳转回去
                redirect_url = f"{login_url}?next={path}"
                return redirect(redirect_url)

        response = self.get_response(request)
        return response